import re
def bin2hex(bin_str):
    bin_int = int(bin_str, 2)
    # 将整数转换为十六进制字符串
    hex_str = format(bin_int, '02x')
    return hex_str
def hex2bin(hex_str):
    hex_int = int(hex_str, 16)
    # 将整数转换为二进制字符串，并补齐到8位
    bin_str = format(hex_int, '08b')
    return bin_str

def ByteToHexStr(byteData):
    i = 2
    if(byteData > 255):
        i = 4
    b=format(byteData, '0{}x'.format(i))
    return b

def bcd_to_int(bcd):
    i_val = bcd & 0xF
    i_val += ((bcd >> 4) & 0xF) * 10
    return i_val

def bcdStr_to_int(bcd_string):
    # 确保输入是字符串
    if not isinstance(bcd_string, str):
        raise ValueError("Input must be a string of hexadecimal digits.")

    # 转换BCD字符串为整数
    integer = 0
    for char in bcd_string:
        # 将每个字符视为十六进制数字，并检查是否在0-9之间
        digit = int(char, 16)
        if digit > 9:
            raise ValueError("Invalid BCD digit: {}".format(char))
        integer = integer * 10 + digit
    return integer

def Dec2HexStr(num):
    hex_string = format(num, '02x')
    return hex_string
def int2str16(num):
    s = hex(num).replace("0x",'')
    if len(s)%2:
        s = "0" + s
    return s
def HexStr2DecInt(hexStr:str):
    #print("hexStr:",hexStr)
    number = int(hexStr, 16)
    return number

def int_to_unsigned_hex(num, width=4):
    if num < 0:
        raise ValueError("Number must be non-negative")
    hex_string = f"{num:0{width}x}"
    return hex_string
# 使用列表推导式和join方法每两位数之间插入空格
def add_spaces_every_two_chars(s):
    s=s.replace(" ","")
    return ' '.join(s[i:i+2] for i in range(0, len(s), 2))

def apdustrTointarray(s):
    lis_by = [] 
    for i in range(0, len(s), 2):
        lis_by.append(int(s[i:i+2],16))
    return lis_by

def dedcode(fram):
    dic={}
    dic["rise"]=fram[2:6]
    dic["contr"]=fram[6:8]
    dic["server_addr"]=fram[8:24]
    dic["verify"]=fram[24:28]
    dic["apdu"]=fram[28:-6]
    return dic
def extract_digits(s):
    return ''.join(re.findall(r'\d', s))
def str2int(data):
    data = int(data,16)
    # data += 1
    data = str(hex(data)).replace("0x","")
    data = "0"*(2-len(str(data))) + data
    return data